<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <script src="../../js/main.js"></script>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --info-color: #17a2b8;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --light-bg: #f8f9fa;
            --card-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }

        body {
            background-color: #f5f7fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #333;
            /*padding: 20px;*/
        }

        .header {
            background: linear-gradient(135deg, var(--secondary-color), #1a2530);
            color: white;
            border-radius: 10px;
            margin-bottom: 25px;
            /*padding: 20px;*/
            box-shadow: var(--card-shadow);
        }

        .card-custom {
            border: none;
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            transition: transform 0.3s ease;
            margin-bottom: 25px;
        }

        .card-custom:hover {
            transform: translateY(-5px);
        }

        .table-container {
            overflow: hidden;
            border-radius: 10px;
        }

        .table thead {
            background: linear-gradient(to right, var(--primary-color), #2980b9);
            color: white;
        }

        .table-hover tbody tr:hover {
            background-color: rgba(52, 152, 219, 0.08);
            transform: scale(1.002);
            transition: all 0.15s ease;
        }

        .action-buttons .btn {
            padding: 0.25rem 0.5rem;
            margin: 0 3px;
            border-radius: 20px;
            font-size: 0.85rem;
        }

        .search-container {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-box {
            flex: 1;
            min-width: 250px;
            border-radius: 25px;
            padding: 10px 20px;
            border: 1px solid #ddd;
            transition: all 0.3s ease;
        }

        .search-box:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.25);
            outline: none;
        }

        .btn-primary {
            background: linear-gradient(to right, var(--primary-color), #2980b9);
            border: none;
            border-radius: 25px;
            padding: 10px 25px;
        }

        .btn-info {
            background: linear-gradient(to right, var(--info-color), #138496);
            border: none;
        }

        .btn-success {
            background: linear-gradient(to right, var(--success-color), #219653);
            border: none;
        }

        .btn-warning {
            background: linear-gradient(to right, var(--warning-color), #e67e22);
            border: none;
        }

        .btn-danger {
            background: linear-gradient(to right, var(--danger-color), #c0392b);
            border: none;
        }

        .pagination .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        @media (max-width: 768px) {
            .search-container {
                flex-direction: column;
                align-items: stretch;
            }

            .action-buttons {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
            }

            .action-buttons .btn {
                margin: 5px;
            }

            .toolbar-wrapper {
                flex-direction: column;
                gap: 15px;
            }

            .page-size-selector {
                width: 100%;
            }
        }

        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
        }

        .modal-header {
            background: linear-gradient(to right, var(--primary-color), #2980b9);
            color: white;
        }

        .role-checkbox {
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 5px;
            background-color: #f8f9fa;
            transition: all 0.2s;
        }

        .role-checkbox:hover {
            background-color: #e9ecef;
        }

        .role-checkbox label {
            cursor: pointer;
            margin-left: 8px;
        }

        .role-list {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 页面标题 -->
    <div class="header text-center">
        <h1><i class="bi bi-people-fill"></i> 用户管理系统</h1>
        <p class="lead">管理用户信息，保障系统安全</p>
    </div>

    <!-- 搜索和操作工具栏 -->
    <div class="card card-custom mb-4">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div class="search-container">
                    <div class="input-group" style="max-width: 500px;">
                        <input type="text" id="searchUserName" class="form-control search-box"
                               placeholder="输入用户名搜索..."
                               onkeydown="if(event.key === 'Enter') loadUserData()">
                        <button class="btn btn-primary" type="button" onclick="loadUserData()">
                            <i class="bi bi-search"></i> 搜索
                        </button>
                    </div>
                </div>

                <button class="btn btn-success mt-2 mt-md-0" onclick="openAddModal()">
                    <i class="bi bi-plus-lg"></i> 新增用户
                </button>
            </div>
        </div>
    </div>

    <!-- 用户数据表格 -->
    <div class="card card-custom">
        <div class="card-body p-0 table-container">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                    <tr>
                        <th>用户ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>联系电话</th>
                        <th>居住地址</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="userTableBody">
                    <!-- 数据将通过JavaScript填充 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 分页控件 -->
        <div class="card-footer">
            <div class="toolbar-wrapper d-flex justify-content-between align-items-center flex-wrap">
                <div class="page-size-selector mb-2 mb-md-0">
                    <select class="form-select form-select-sm" id="pageSize" onchange="handlePageSizeChange()">
                        <option value="5">每页5条</option>
                        <option value="10" selected>每页10条</option>
                        <option value="20">每页20条</option>
                        <option value="50">每页50条</option>
                    </select>
                </div>

                <nav>
                    <ul class="pagination justify-content-center mb-0" id="pagination">
                        <!-- 分页将通过JavaScript填充 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<!-- 新增用户模态框 -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-person-plus"></i> 新增用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addForm">
                    <div class="mb-3">
                        <label class="form-label">用户名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="addUserName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码 <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="addPassword" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="addEmail">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">联系电话</label>
                        <input type="tel" class="form-control" id="addMobile">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">居住地址</label>
                        <input type="text" class="form-control" id="addAddress">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveNewUser()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil-square"></i> 编辑用户信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <input type="hidden" id="editUserId">
                    <div class="mb-3">
                        <label class="form-label">用户ID</label>
                        <input type="text" class="form-control" id="displayUserId" disabled>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="editUserName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="editEmail">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">联系电话</label>
                        <input type="tel" class="form-control" id="editMobile">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">居住地址</label>
                        <input type="text" class="form-control" id="editAddress">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveEdit()">保存修改</button>
            </div>
        </div>
    </div>
</div>

<!-- 角色分配模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-person-badge"></i> 分配用户角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-control" id="roleUserName" disabled>
                </div>
                <div class="mb-3">
                    <label class="form-label">分配角色</label>
                    <div class="role-list" id="roleList">
                        <!-- 角色将通过JavaScript填充 -->
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveUserRoles()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 通知容器 -->
<div class="toast-container"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 初始化变量
    currentPage = 1;
    pageSize = parseInt(document.getElementById('pageSize').value);
    currentUserId = 0;
    allRoles = [];
    selectedRoleIds = [];

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 加载用户数据
        loadUserData();

        // 加载所有角色
        loadAllRoles();
    });

    // 处理分页大小变化
    function handlePageSizeChange() {
        pageSize = parseInt(document.getElementById('pageSize').value);
        currentPage = 1;
        loadUserData();
    }
    loadUserData(1)
    // 加载用户数据
    function loadUserData(page = currentPage) {
        const userName = document.getElementById('searchUserName').value;
        currentPage = page;

        // AJAX请求获取用户数据
        fetch(`/sysUser/pageUser?userName=${encodeURIComponent(userName)}&current=${page}&size=${pageSize}`)
            .then(response => response.json())
            .then(data => {
                renderTable(data.records);
                renderPagination(data);
            })
            .catch(error => {
                console.error('获取用户数据失败:', error);
                showToast('获取用户数据失败', 'danger');
            });
    }

    // 渲染表格
    function renderTable(users) {
        const tbody = document.getElementById('userTableBody');
        tbody.innerHTML = '';

        if (!users || users.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center py-4 text-muted">
                        <i class="bi bi-search me-2"></i>没有找到符合条件的用户
                    </td>
                </tr>
            `;
            return;
        }

        users.forEach(user => {
            const row = document.createElement('tr');

            row.innerHTML = `
                <td>${user.userId}</td>
                <td>${user.userName}</td>
                <td>${user.email || '--'}</td>
                <td>${user.mobile || '--'}</td>
                <td>${user.address || '--'}</td>
                <td class="action-buttons">
                    <button class="btn btn-sm btn-outline-primary"
                        onclick="openEditModal(${user.userId}, '${user.userName}', '${user.email || ''}', '${user.mobile || ''}', '${user.address || ''}')">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-outline-info"
                        onclick="openRoleModal(${user.userId}, '${user.userName}')">
                        <i class="bi bi-person-badge"></i> 权限
                    </button>
                    <button class="btn btn-sm btn-outline-danger"
                        onclick="deleteUser(${user.userId})">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            `;

            tbody.appendChild(row);
        });
    }

    // 渲染分页控件
    function renderPagination(pageInfo) {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        // 首页
        pagination.innerHTML += `
            <li class="page-item ${pageInfo.current === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="loadUserData(1)">首页</a>
            </li>
        `;

        // 上一页
        pagination.innerHTML += `
            <li class="page-item ${pageInfo.current === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="loadUserData(${pageInfo.current - 1})">«</a>
            </li>
        `;

        // 页码
        const startPage = Math.max(1, pageInfo.current - 2);
        const endPage = Math.min(pageInfo.pages, pageInfo.current + 2);

        for (let i = startPage; i <= endPage; i++) {
            pagination.innerHTML += `
                <li class="page-item ${i === pageInfo.current ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="loadUserData(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页
        pagination.innerHTML += `
            <li class="page-item ${pageInfo.current === pageInfo.pages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="loadUserData(${pageInfo.current + 1})">»</a>
            </li>
        `;

        // 尾页
        pagination.innerHTML += `
            <li class="page-item ${pageInfo.current === pageInfo.pages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="loadUserData(${pageInfo.pages})">尾页</a>
            </li>
        `;
    }

    // 打开新增用户模态框
    function openAddModal() {
        document.getElementById('addForm').reset();
        const modal = new bootstrap.Modal(document.getElementById('addModal'));
        modal.show();
    }

    // 保存新用户
    function saveNewUser() {
        const user = {
            userName: document.getElementById('addUserName').value,
            password: document.getElementById('addPassword').value,
            email: document.getElementById('addEmail').value,
            mobile: document.getElementById('addMobile').value,
            address: document.getElementById('addAddress').value
        };

        if (!user.userName || !user.password) {
            showToast('用户名和密码不能为空', 'warning');
            return;
        }

        // AJAX请求保存新用户
        fetch('/sysUser/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(user)
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('保存失败');
            })
            .then(result => {
                if (result === 'success') {
                    bootstrap.Modal.getInstance(document.getElementById('addModal')).hide();
                    loadUserData();
                    showToast('用户添加成功', 'success');
                } else {
                    throw new Error('保存失败');
                }
            })
            .catch(error => {
                console.error('保存用户失败:', error);
                showToast('保存用户失败', 'danger');
            });
    }

    // 打开编辑模态框
    function openEditModal(userId, userName, email, mobile, address) {
        document.getElementById('editUserId').value = userId;
        document.getElementById('displayUserId').value = userId;
        document.getElementById('editUserName').value = userName;
        document.getElementById('editEmail').value = email || '';
        document.getElementById('editMobile').value = mobile || '';
        document.getElementById('editAddress').value = address || '';

        const modal = new bootstrap.Modal(document.getElementById('editModal'));
        modal.show();
    }

    // 保存编辑
    function saveEdit() {
        const user = {
            userId: document.getElementById('editUserId').value,
            userName: document.getElementById('editUserName').value,
            email: document.getElementById('editEmail').value,
            mobile: document.getElementById('editMobile').value,
            address: document.getElementById('editAddress').value
        };

        if (!user.userName) {
            showToast('用户名不能为空', 'warning');
            return;
        }

        // AJAX请求更新用户信息
        fetch('/sysUser/updateUser', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(user)
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('更新失败');
            })
            .then(result => {
                if (result === 'success') {
                    bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
                    loadUserData(currentPage);
                    showToast('用户信息更新成功', 'success');
                } else {
                    throw new Error('更新失败');
                }
            })
            .catch(error => {
                console.error('更新用户失败:', error);
                showToast('更新用户失败', 'danger');
            });
    }

    // 删除用户
    function deleteUser(userId) {
        if (!confirm(`确定要删除用户ID为 ${userId} 的用户吗？`)) return;

        // AJAX请求删除用户
        fetch(`/sysUser/delUser/${userId}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('删除失败');
            })
            .then(result => {
                if (result === 'success') {
                    loadUserData(currentPage);
                    showToast('用户删除成功', 'success');
                } else {
                    throw new Error('删除失败');
                }
            })
            .catch(error => {
                console.error('删除用户失败:', error);
                showToast('删除用户失败', 'danger');
            });
    }

    // 加载所有角色
    loadAllRoles()
    function loadAllRoles() {
        fetch('/sysRole/getAllRole')
            .then(response => response.json())
            .then(data => {
                if (data.code === "200") {
                    allRoles = data.data;
                }
            })
            .catch(error => {
                console.error('获取角色列表失败:', error);
            });
    }

    // 打开角色分配模态框
    function openRoleModal(userId, userName) {
        currentUserId = userId;
        document.getElementById('roleUserName').value = userName;

        // 获取用户已有角色
        fetch(`/sysUserRole/${userId}`)
            .then(response => response.json())
            .then(roleIds => {
                selectedRoleIds = roleIds;
                renderRoleList();
                const modal = new bootstrap.Modal(document.getElementById('roleModal'));
                modal.show();
            })
            .catch(error => {
                console.error('获取用户角色失败:', error);
                showToast('获取用户角色失败', 'danger');
            });
    }

    // 渲染角色列表
    function renderRoleList() {
        const roleList = document.getElementById('roleList');
        roleList.innerHTML = '';
        console.log(allRoles)
        if (!allRoles || allRoles.length === 0) {
            roleList.innerHTML = '<div class="text-center py-3 text-muted">没有可用角色</div>';
            return;
        }

        allRoles.forEach(role => {
            const roleItem = document.createElement('div');
            roleItem.className = 'role-checkbox';

            const isChecked = selectedRoleIds.includes(role.roleId);

            roleItem.innerHTML = `
                <div class="form-check">
                    <input class="form-check-input" name="radio" type="radio"
                           id="${role.roleId}"
                           ${isChecked ? 'checked' : ''}
                           onchange="toggleRole(${role.roleId}, this.checked)">
                    <label class="form-check-label" for="role_${role.roleId}">
                        ${role.roleName} (${role.description || '无描述'})
                    </label>
                </div>
            `;

            roleList.appendChild(roleItem);
        });
    }

    // 切换角色选择状态
    function toggleRole(roleId, isChecked) {
        if (isChecked) {
            if (!selectedRoleIds.includes(roleId)) {
                selectedRoleIds.push(roleId);
            }
        } else {
            const index = selectedRoleIds.indexOf(roleId);
            if (index > -1) {
                selectedRoleIds.splice(index, 1);
            }
        }
    }

    // 保存用户角色
    function saveUserRoles() {
        const selectedRole = document.querySelector('input[name="radio"]:checked');
        let idd = selectedRole.id
        // AJAX请求保存用户角色
        fetch(`/sysUserRole/save/${currentUserId}/${idd}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(selectedRole)
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('保存失败');
            })
            .then(result => {
                if (result === 'success') {
                    bootstrap.Modal.getInstance(document.getElementById('roleModal')).hide();
                    showToast('用户角色分配成功', 'success');
                } else {
                    throw new Error('保存失败');
                }
            })
            .catch(error => {
                console.error('保存用户角色失败:', error);
                showToast('保存用户角色失败', 'danger');
            });
    }

    // 显示通知
    function showToast(message, type = 'success') {
        const toastContainer = document.querySelector('.toast-container');
        const toastId = `toast-${Date.now()}`;

        const toast = document.createElement('div');
        toast.className = `toast align-items-center text-white bg-${type} border-0`;
        toast.setAttribute('role', 'alert');
        toast.setAttribute('aria-live', 'assertive');
        toast.setAttribute('aria-atomic', 'true');
        toast.id = toastId;

        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    <i class="bi ${type === 'success' ? 'bi-check-circle' : type === 'warning' ? 'bi-exclamation-triangle' : 'bi-x-circle'} me-2"></i>
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        `;

        toastContainer.appendChild(toast);

        // 显示toast
        const bsToast = new bootstrap.Toast(toast);
        bsToast.show();

        // 自动移除toast
        setTimeout(() => {
            bsToast.dispose();
            toast.remove();
        }, 3000);
    }
</script>
</body>
</html>